#!/bin/bash

# 设置项目根目录
PROJECT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$PROJECT_DIR"

# PID文件路径
PID_FILE="logs/app.pid"

# 检查PID文件是否存在
if [ ! -f "$PID_FILE" ]; then
    echo "PID file not found. Application might not be running."
    exit 0
fi

# 读取PID
PID=$(cat "$PID_FILE")

# 检查进程是否存在
if ! ps -p $PID > /dev/null 2>&1; then
    echo "Process not found. Cleaning up PID file..."
    rm "$PID_FILE"
    exit 0
fi

# 尝试优雅停止
echo "Stopping application (PID: $PID)..."
kill -TERM $PID

# 等待进程结束
WAIT_TIME=0
while ps -p $PID > /dev/null 2>&1; do
    if [ $WAIT_TIME -gt 30 ]; then
        echo "Process did not stop gracefully. Forcing shutdown..."
        kill -9 $PID
        break
    fi
    sleep 1
    ((WAIT_TIME++))
done

# 删除PID文件
rm "$PID_FILE"

echo "Application stopped successfully"
